extends CanvasLayer


onready var name_input = $VBoxContainer/name/name/name
onready var type_op = $VBoxContainer/name/type/typeOp
onready var remark_input = $VBoxContainer/desc/remark

# 这个移除
onready var reward_items_op = $VBoxContainer/rewards_item/HBoxContainer/OptionButton

onready var a_repeat_op = $VBoxContainer/rewards_item/OptionButton

onready var fail_back_op = $"VBoxContainer/TabContainer/剧本关联控制/name/back/typeOp"

onready var gl_next_drama_op = $"VBoxContainer/TabContainer/剧本关联控制/finsh2/drama/OptionButton"
onready var gl_clear_drama_op = $"VBoxContainer/TabContainer/剧本关联控制/clear2/drama2/OptionButton"
onready var gl_back_drama_op = $"VBoxContainer/TabContainer/剧本关联控制/name/back_drama2/OptionButton"

onready var Interrupt_completion_op = $"VBoxContainer/TabContainer/剧本意外中断处理/title/filshh/typeOp"
onready var interrupt_back_pokemon_center_op = $"VBoxContainer/TabContainer/剧本意外中断处理/title/type/typeOp"
onready var interrupt_reset_role_position_input = $"VBoxContainer/TabContainer/剧本意外中断处理/desc/edit"
onready var drama_start_state_form = $"VBoxContainer/TabContainer/场景布局"
onready var drama_sequence_form = $"VBoxContainer/TabContainer/表演流程"


onready var drama_hinder_op = $VBoxContainer/dramas2/HBoxContainer/OptionButton
onready var drama_next_normal_hinder_op = $VBoxContainer/dramas2/HBoxContainer2/OptionButton



signal close()

var edit_data = {
	"rewardItems":"",
	"next":"",
	"backIds":"",
	"clearIds":"",
	"drama_hinder":[],
	"drama_next_normal_hinder":[],
}

# 对剧本数据缓存一下，每次进来都缓存一下，加快加载的速度
# 由于查询的时候每次都是循环，会很慢
var cache_drama = {
	
}

var init = false

# 默认不是编辑
var edit = false
func _ready():
	pass 


func set_edit_data(data):
	if data and !init:
		init = true
		edit = true
		self.edit_data = data
	else:
		init = true
		edit = false
	
	for item in DataSource.get_data_list(DataSource.drama):
		cache_drama[str(item["id"])] = item

	name_input.text = data.get("name", "")
	type_op.select(type_op.get_item_index(data.get("type", 1)))
	remark_input.text = data.get("remark", "")
	
	# 移除
#	reward_items_input.text = data["rewardItems"]
	
	# 道具添加
	var rewards = data.get("rewardItems","").split(",")
	reward_build(rewards)
	
#	var index =  0
#	reward_items_op.clear()
#	for item in rewards:
#		if !item || item.find(":") == -1: continue
#		index += 1
#		var temp  = item.split(":")
#		var item_id = int(temp[0])
#		var item_count = int(temp[1])
#		var item_info = DataSource.get_item_by_id(item_id)
#		reward_items_op.add_item(str("[%d]%s x %d" % [ item_info["id"] ,item_info["name"], item_count] ) , index)
#
	a_repeat_op.select(a_repeat_op.get_item_index(data.get("aRepeat", 0)))
	
	
	fail_back_op.select(fail_back_op.get_item_index(data.get("failBack", 0)))
	# 下面三个弃用

	
	Interrupt_completion_op.select(Interrupt_completion_op.get_item_index(data.get("InterruptCompletion", 0)))
	interrupt_back_pokemon_center_op.select(interrupt_back_pokemon_center_op.get_item_index(data.get("interruptBackPokemonCenter", 0)))
	
	interrupt_reset_role_position_input.text = data.get("interruptResetRolePosition","0")
	
	drama_start_state_form.set_data(data.get("drama_start_state",[]))
	drama_sequence_form.set_data(data.get("drama_sequence"))
	
	# 这两个弃用

	var hinders = {
		"drama_hinder":drama_hinder_op,
		"drama_next_normal_hinder":drama_next_normal_hinder_op,
	}
	for key in hinders.keys():
		_hinder_build(key,hinders[key])
	
	
	var uis = {
		"next":gl_next_drama_op,
		"clearIds":gl_clear_drama_op,
		"backIds":gl_back_drama_op
	}
	
	
	for key in uis.keys():
		var ui = uis[key]
		_ids_build(key,ui)
#
#		ui.clear()
#		for item in data[key].split(","):
#			if !item: continue
#			var info = cache_drama[str(item)]
#			ui.add_item(str("[%s]%s" % [info["id"],info["name"]]),int(info["id"]))
#			pass
#		pass
	$btns/ok.text = "保存"

func _hinder_build(key,container):
	container.clear()
	for item in edit_data.get(key,[]):
		if !item: continue
		var info = cache_drama[str(item)]
		container.add_item(str("[%s]%s" % [info["id"],info["name"]]),int(info["id"]))

func _ids_build(key,container):
	container.clear()
	for item in edit_data[key].split(","):
		if !item: continue
		var info = cache_drama[str(item)]
		container.add_item(str("[%s]%s" % [info["id"],info["name"]]),int(info["id"]))
func reward_build(rewards):
	var index =  0
	reward_items_op.clear()
	for item in rewards:
		if !item || item.find(":") == -1: continue
		index += 1
		var temp  = item.split(":")
		var item_id = int(temp[0])
		var item_count = int(temp[1])
		var item_info = DataSource.get_item_by_id(item_id)
		reward_items_op.add_item(str("[%d]%s x %d" % [ item_info["id"] ,item_info["name"], item_count] ) , index)


func ids_to_str(list):
	var s = ""
	for i in range(list.size()):
		if i != 0:
			s += ","
		
		s += str(list[i])
	
	return s	

func str_to_ids(s)->Array:
	var temp_arr = []
	for item in s.split(","):
		if item: temp_arr.append(item)
	return temp_arr

func _on_cancel_button_up():
	MainTool.getUILayer().pop_ui()


func get_data():
	var name = name_input.text
	var type = type_op.get_selected_id()
	var remark = remark_input.text
	
	var reward_items = edit_data.get("rewardItems","")
	var next = edit_data.get("next","")
	var back_ids = edit_data.get("backIds","")
	var clear_ids = edit_data.get("clearIds","")
	var drama_hinder = edit_data.get("drama_hinder",[])
	var drama_next_normal_hinder = edit_data.get("drama_next_normal_hinder",[])
#
	
#	var reward_items = new_data.get("rewardItems")
#	var next = new_data.get("next")
#	var back_ids = new_data.get("backIds")
#	var clear_ids = new_data.get("clearIds")
#	var drama_hinder = new_data.get("drama_hinder")
#	var drama_next_normal_hinder = new_data.get("drama_next_normal_hinder")
	
	
	var a_repeat = a_repeat_op.get_selected_id()
	var fail_back = fail_back_op.get_selected_id()
	
	
	var Interrupt_completion = Interrupt_completion_op.get_selected_id()
	var interrupt_back_pokemon_center = interrupt_back_pokemon_center_op.get_selected_id()
	var interrupt_reset_role_position = interrupt_reset_role_position_input.text
	
	var drama_start_state = drama_start_state_form.get_data()
	var drama_sequence = drama_sequence_form.get_data()
	
	
	return {
		"name": name,
		"type": type,
		"remark": remark,
		"rewardItems": reward_items,
		"Arepeat": a_repeat,
		"backIds": back_ids,
		"next": next,
		"failBack": fail_back,
		"clearIds": clear_ids,
		"InterruptCompletion": Interrupt_completion,
		"interruptBackPokemonCenter": interrupt_back_pokemon_center,
		"interruptResetRolePosition": interrupt_reset_role_position,
		"drama_start_state": drama_start_state,
		"drama_sequence": drama_sequence,
		"drama_hinder": drama_hinder,
		"drama_next_normal_hinder": drama_next_normal_hinder,
	}
	

func read_form(dic):
	var data = get_data()
	
	for key in data.keys():
		dic[key] = data[key]


func _on_ok_button_up():
	if edit:
		read_form(edit_data)
		DataSource.update_data(DataSource.drama, edit_data)
	else:
		var data = {}
		read_form(data)
		
		data["id"] = get_drama_id()
		
		DataSource.add_data(DataSource.drama, data)
	
	MainTool.getUILayer().pop_ui()
	emit_signal("close")


func get_drama_id():
	var dramas = DataSource.get_data_list(DataSource.drama)
	
	var max_id = 0
	for data in dramas:
		max_id = max(max_id, int(data["id"]))
	
	return str(max_id + 1)

func _add_next_drama(index,value):
	_d("next",index)
	pass
func _add_clear_drama(index,value):
	_d("clearIds",index)
	pass
func _add_back_drama(index,value):
	_d("backIds",index)
	pass
# 添加阻碍剧本
func _add_hinder_drama(index,value):
	var dramas = DataSource.get_data_list(DataSource.drama)
	edit_data["drama_hinder"].append(str(dramas[index]["id"]))

	_hinder_build("drama_hinder",drama_hinder_op)
	pass
# 添加关联剧本
func _add_normal_hinder_drama(index,value):
	var dramas = DataSource.get_data_list(DataSource.drama)
	edit_data["drama_next_normal_hinder"].append(str(dramas[index]["id"]))

	_hinder_build("drama_next_normal_hinder",drama_next_normal_hinder_op)
	pass
func _d(key,index):
	var dramas = DataSource.get_data_list(DataSource.drama)
	# 这个是添加的剧本
	var add_info = dramas[index]
	# 将值转换回去
	var ids = str_to_ids(edit_data[key])
	ids.append(add_info["id"])
	edit_data[key] = ids_to_str(ids)

	var uis = {
		"next":gl_next_drama_op,
		"clearIds":gl_clear_drama_op,
		"backIds":gl_back_drama_op
	}
	_ids_build(key,uis[key])
	pass
# 点击了添加按钮
func _on_Add_pressed(extra_arg_0):
	var title = ""
	var list_data = []
	var call_back_func = ""
	
	for item in DataSource.get_data_list(DataSource.drama):
		list_data.append(str("[%s]%s" % [item["id"],item["name"]]))
	
	if extra_arg_0 == "next":
		title = "请选择需要添加的剧本"
		call_back_func = "_add_next_drama"
	elif extra_arg_0 == "clearIds":
		title = "请选择需要移除的剧本"
		call_back_func = "_add_clear_drama"
	elif extra_arg_0 == "backIds":
		title = "请选择需要回退的剧本"
		call_back_func = "_add_back_drama"
	elif extra_arg_0 == "hinder":
		title = "请选择剧本"
		call_back_func = "_add_hinder_drama"
		pass
	elif extra_arg_0 == "normal_hinder":
		title = "请选择剧本"
		call_back_func = "_add_normal_hinder_drama"
		pass
	# 显示这个ui
	var ui = MainTool.getUILayer().add_ui("res://tool/common/PopUp/ListSearchPopup.tscn", 0, false)
	ui.set_data(title,list_data,funcref(self,call_back_func))
	ui.popup_centered()
	pass

# 点击了移除按钮
func _on_Remove_pressed(extra_arg_0):
	var uis = {
		"next":gl_next_drama_op,
		"clearIds":gl_clear_drama_op,
		"backIds":gl_back_drama_op
	}
	if extra_arg_0 == "next" || extra_arg_0 == "clearIds" || extra_arg_0 == "backIds":
		# 需要移除的id
		var ui = uis[extra_arg_0]
		var id = str(ui.get_selected_id())
		var ids = str_to_ids(edit_data[extra_arg_0])
		ids.erase(id)
		edit_data[extra_arg_0] = ids_to_str(ids)
		_ids_build(extra_arg_0,uis[extra_arg_0])
		pass
	elif extra_arg_0 == "hinder":
		var id = drama_hinder_op.get_selected_id()
		edit_data["drama_hinder"].erase(str(id))
		_hinder_build("drama_hinder",drama_hinder_op)
		pass
	elif extra_arg_0 == "normal_hinder":
		var id = drama_next_normal_hinder_op.get_selected_id()
		edit_data["drama_next_normal_hinder"].erase(str(id))
		_hinder_build("drama_next_normal_hinder",drama_next_normal_hinder_op)
		pass
	
	pass

var current_select_item_info = null
func _item_select_calback(index,value):
	var item_list = DataSource.get_serie_item_list()
	current_select_item_info = item_list[index]
	yield(get_tree().create_timer(0.2),"timeout")
	var ui = MainTool.getUILayer().add_ui("res://tool/common/PopUp/SpinBoxLineEditPopup.tscn", 0, false)
	ui.set_data("请输入数量",funcref(self,"_item_select_count_calback"))
	ui.popup_centered()
	pass
func _item_select_count_calback(type,value):
	if current_select_item_info == null: return
	if type == 0:
		current_select_item_info = null
		return
	
	var txt = edit_data.get("rewardItems","")
	var add_item = str("%d:%d" % [ current_select_item_info["id"],value ])
	if edit_data.get("rewardItems",""):
		edit_data["rewardItems"] += str(",",add_item)
	else:
		edit_data["rewardItems"] += str(add_item)
	
	
	current_select_item_info = null
	
	var rewards = edit_data.get("rewardItems","").split(",")
	reward_build(rewards)
	pass
# 添加奖励
func _on_Add_rewards_pressed():
	
	var item_list = DataSource.get_serie_item_list()
	var list_data = []
	for item  in item_list:
		list_data.append(str("[%d] %s" % [ item["id"],item["name"] ] ) )
	var ui = MainTool.getUILayer().add_ui("res://tool/common/PopUp/ListSearchPopup.tscn", 0, false)
	ui.set_data("请选择道具",list_data,funcref(self,"_item_select_calback"))
	ui.popup_centered()
	pass # Replace with function body.

# 移除奖励
func _on_Remove_rewards_pressed():
	var index = reward_items_op.get_selected_id()
	if index <= 0: return
	var txt = edit_data.get("rewardItems","")
	
	var temp_new =  []
	var i = 1
	
	for item in txt.split(","):
		if i == index || !item: continue
		temp_new.append(item)
		i += 1
	edit_data["rewardItems"] = ids_to_str(temp_new)


	var rewards = edit_data.get("rewardItems","").split(",")
	reward_build(rewards)
	pass # Replace with function body.
